<?php
/*
 * @See Clu_Db_Table_Abstract
 */
class article_Model_Service extends Zend_Db_Table_Abstract
{
    //only specify the table name, everything else inherits
	protected $_name = "articles";
	protected $_primary = "article_id";

	/**
	 * @return Zend_Db_Table_Row object;
	 */
	public function findByPrimary($id)
	{
		if (!$id)
            return null;
        else
		    return $this->fetchRow('article_id = ' . $this->getAdapter()->quote($id, 'INTEGER'));
	}
	
	/*
	 * return array or null
	 */
	public function getArticleData($id)
	{
		
    	if (!$a = $this->findByPrimary($id))
        {
            return null;
        }
	    $viewLang = Zend_Registry::get('viewLang'); 
	    
        //Find translation data if viewLang is not the original language of the article
        if ($a['article_language'] != $viewLang)
        {
        	//require_once APP_PATH . '/modules/article/Model/Translation.php';
        	$mTranslation = new article_Model_Translation();
    		if ($t = $mTranslation->findByPrimary(array('id'=>$id,'language'=>$viewLang)))
            {	
//            	die_a($t->toArray());
                $a['article_title']         = $t['title'];
                $a['article_body']          = $t['body'];
				$a['article_language']		= $viewLang;
                $a['article_keywords']      = $t['keywords'];
                $a['article_filtered_body'] = $t['body'];
                
                /*
                $bodyFilter = new Clu_Filter_HtmlBody();
        		$a['article_filtered_body'] = $bodyFilter->filter($t['body']);
				*/
            }
            else
            {
            	//not yet translated to '$viewLang'
            }	
        }
        return $a->toArray();
	}
	
	
	public function insertRaw($data, $doValidate = false)
	{
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity())
        {
        	die('Not yet logged in to post an article');
        	return false;
        }	
		if ($doValidate)
			die("not yet implemented");
		$a = array();
	    $a['article_title'] 		= isset($data['article_title']) ? $data['article_title'] : null;
	    $a['article_module'] 		= isset($data['article_module']) ? $data['article_module'] : null;
	    $a['article_keywords'] 		= isset($data['article_keywords']) ? $data['article_keywords'] : null;
	    $a['article_body'] 			= isset($data['article_body']) ? $data['article_body'] : "NULL";
		
	    $a['article_language'] 		= isset($data['article_language']) ? $data['article_language'] :
			Zend_Registry::get('configuration')->general->defaultNodeLanguage->article;
	    $a['article_status']        = isset($data['article_status']) ? $data['article_status'] : 
			Zend_Registry::get('configuration')->general->defaultNodeStatus;
		if (isset($data['poster_id']))
			$a['article_poster_id'] = $data['poster_id'];
		else
	    	$a['article_poster_id'] = $auth->getIdentity()->id;
        $a['article_post_time'] 	= time();
		
        //TODO: Move this post-filter
        if (!empty($a['article_body']))
        {
            $bodyFilter = new Clu_Filter_HtmlBody();
            $a['article_filtered_body'] = $bodyFilter->filter($a['article_body']);
        }
        return $this->insert($a);
	}

	
	/**
	 * @param $a The article table object
	 * @param $data: array of article data
	 * @param $id: article id when $a is not provided
	 */
	public function saveRaw($a, $data, $id, $doValidate)
	{
	    if ((!$a) && (!$id))
	    	return false;
	    else if (!$a)
	       	if (!$a = $this->findByPrimary($id))
	       		return false;

	    $auth = Zend_Auth::getInstance();
	    $data['article_updater_id']  = $auth->getIdentity()->id;
        $data['article_update_time'] = time();
	    if ($doValidate)
	    {
	    	//Validate Data here
	    }
        //TODO: Move this post-filter
        if (!empty($a['article_body']))
        {
            $bodyFilter = new Clu_Filter_HtmlBody();
            $a['article_filtered_body'] = $bodyFilter->filter($a['article_body']);
        }
	    
	    $a->setFromArray($data);
        return $a->save();
	}

	/**
	 * @param 
	 * 		$data['status']: New status to update ('published','unpublished', 'deleted', 'queued')
	 * @param 
	 * 		$data['statuschange_reason']: Why the status needs to be changed
	 */
	
	
	/**
	 * $idArray:: Array of primary keys
	 * @param $atomic::Boolean whether or not to perform the delete atomically
	 * @return boolean
	 */
	public function deleteByPrimary($idArray, $atomic = true)
	{	//return true;
        $db = $this->getAdapter();
        $auth = Zend_Auth::getInstance();
       	$uIdentity = $auth->getIdentity();
		$sess = new Zend_Session_Namespace(CLU_NS);
		
		if(is_array($idArray))
		{
			foreach($idArray as $idList)
			{
				$tmp = $this->findByPrimary($idList);
				$articles[] = $tmp['article_poster_id'];
			}
		}
		else
		{
			$tmp = $this->findByPrimary($idArray);
			$articles = $tmp['article_poster_id'];
		}	
		
		if ($atomic)
	        $db->beginTransaction();
	    //user is not admin
	    if(strpos ($sess->userPermissions, 'administer everything') === false)
	    {
			if (($uIdentity->id != $db->quote($articles, 'INTEGER') && strpos ($sess->userPermissions, 'delete article') === false) || 
				($uIdentity->id == $db->quote($articles, 'INTEGER') && strpos ($sess->userPermissions, 'delete article') === false))
			{
				return false;
			}
			else 
			{
				try
	        	{
		            $sql1 = "DELETE FROM articles WHERE article_id IN (". $db->quote($idArray, 'INTEGER') .")" ;
		           	$db->query($sql1);
		           	$sql2 = "DELETE FROM article_translations WHERE original_article_id IN (". $db->quote($idArray, 'INTEGER') .")" ;
		           	$db->query($sql2);
		           	
		           	if ($atomic)
	    	            $db->commit();
	                return true;
	    		}
				catch (Exception $e)
	            {
	                if ($atomic)
	    	            $db->rollBack();
	                return false;
	            }
			}
	    }
	    else// if user is admin
	    {
	    	try
        	{
	            $sql1 = "DELETE FROM articles WHERE article_id IN (". $db->quote($idArray, 'INTEGER') .")" ;
	           	$db->query($sql1);
	           	$sql2 = "DELETE FROM article_translations WHERE original_article_id IN (". $db->quote($idArray, 'INTEGER') .")" ;
	           	$db->query($sql2);
	           	
	           	if ($atomic)
    	            $db->commit();
                return true;
    		}
			catch (Exception $e)
            {
                if ($atomic)
    	            $db->rollBack();
                return false;
            }
	    }
	}

	public function search($data)
	{
		$status 				= isset($data['status']) ? $data['status']:null;
		$module 				= isset($data['modules']) ? $data['modules'] : null;
		$langOp 				= isset($data['languageOperator']) ? $data['languageOperator'] : null; 
		$language 				= isset($data['language']) ? $data['language']:null;
 		$translator_id			= isset($data['translator_id']) ? $data['translator_id']:null;
     	$poster_id				= isset($data['poster_id']) ? $data['poster_id'] :null;
     	$post_timeOperator		= isset($data['post_timeOperator']) ? $data['post_timeOperator'] :null;
     	$update_timeOperator	= isset($data['update_timeOperator']) ? $data['update_timeOperator'] :null;
     	$originality			= isset($data['article_originality']) ? $data['article_originality'] :null;
     	
    	//select SQL query
    	$db = $this->getAdapter();
		$select = $db->select()
				     ->distinct();
		//only inner join with article_translations when lang operator is 'been_translated 
		// or 'not translated'. Other cases are : 'origin in' and 'all' does not touch the translations table
        $select->from( array('a' => 'articles') );
		if ($langOp == 'been_translated' || $langOp == 'not_translated')
		{
       		$select->from(array('at' => 'article_translations'),'');
		}
		
        if ($status != 'all' && $status )
      		$select->where('a.article_status = ?', $db->quoteinto($status,'STRING')); 
      	
      	if ($module != 'all' && $module )
      		$select->where('a.article_module = ?', $db->quoteinto($module,'STRING')); 
      	if ($originality != 'all')
      		$select->where('a.article_originality = ?', $db->quoteinto($originality,'STRING')); 	
      	if ($translator_id )
      		$select->where('at.translate_poster_id = ?', (int)$db->quote($translator_id,"INT")); 
		if ($poster_id )
      		$select->where('a.article_poster_id = ?', (int)$db->quote($poster_id,"INT")); 
     		
  		$tmp  = 60*60*24 ;
		$time = getdate();
		switch($post_timeOperator)
		{
			case 1:
			{
				$select->where('a.article_post_time >= ?',($time['0'] - $tmp*7));
				break;
			}
			case 2:
			{
				$select->where('a.article_post_time >= ?',($time['0'] - $tmp*30));
				break;
			}
			case 3:
			{
				$select->where('a.article_post_time >= ?',($time['0'] - $tmp*60));
				break;
			}
		}  
		
	 	if ($langOp == 'origin')
		{ 	 
			if($language != 'all')
				$select->where('a.article_language = ?',$db->quoteinto($language,'STRING'));
		}
		else if ($langOp == 'been_translated')
		{
			if($language != 'all') //have been translated to $language
			{
				$sql = " AND (at.language = '$language' AND a.article_id = at.original_article_id) OR a.article_language = '$language' ";
				$select->where($sql);
			}
			else //have been translated to all languages
			{
				$select->where('a.article_id = at.original_article_id')
						->group('a.article_id')
						->having('count(at.language)=3');
			}
		}
		else if ($langOp == 'not_translated')
		{
			if($language == 'all')
			{
				$sql = "(SELECT DISTINCT `a2`.article_id FROM `article_translations` AS `at2` INNER JOIN `articles` AS `a2` 
						WHERE a2.article_id = at2.original_article_id GROUP BY a2.article_id HAVING COUNT(at2.language)=3)";
				$select->where("a.article_id NOT IN ".$sql);
			}
			else  //not yet translated to $language
			{
				//all the articles that have been translated to $language. Copied from above
				$sql = "(SELECT DISTINCT `a2`.article_id FROM `article_translations` AS `at2` INNER JOIN `articles` AS `a2` 
						WHERE (at2.language = '$language' AND a2.article_id = at2.original_article_id) OR a2.article_language = '$language')";
				$select->where("a.article_id NOT IN ".$sql);		
			}
		}
//		die($select);
		return $select;
	}
	
	public function bulkUpdateStatus($idArray, $data, $atomic = true)
    {
        $idList = implode (',', $idArray);
        $db = $this->getAdapter() ;
        if ($atomic)
        	$db->beginTransaction();
        try 
        {
            $sql =  "UPDATE articles SET article_status = ".$db->quote($data['status'],'STRING')." WHERE article_id IN (".$idList.")" ;
//            die($sql);
            $db->query($sql);
            if ($atomic)
            	$db->commit();
            return true;
        }    
        catch (Exception $e)
        {
        	die($e->getMessase());
        	if ($atomic)
            	$db->rollBack();
            return false;
        }           
     }
}
?>
